<template>
    <view class="login-container">
        <view class="header" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
            <text class="title">用户登录</text>
        </view>

        <!-- #ifdef MP-WEIXIN -->
        <view class="form-container">
            <view class="form-group">
                <input
                    class="input"
                    type="text"
                    placeholder="请输入用户名"
                    v-model="formData.username"
                />
                <input
                    class="input"
                    password
                    placeholder="请输入密码"
                    v-model="formData.password"
                />
            </view>
            <button 
                class="login-btn"
                :loading="loading"
                @click="handleMiniLogin"
            >立即登录</button>
        </view>
        <!-- #endif -->

        <!-- #ifdef H5 -->
        <view class="tab-bar">
            <text 
                :class="['tab-item', activeTab === 0 && 'active']"
                @click="activeTab = 0"
            >账号登录</text>
            <text 
                :class="['tab-item', activeTab === 1 && 'active']"
                @click="activeTab = 1"
            >手机登录</text>
        </view>

        <view class="form-container">
            <view v-if="activeTab === 0" class="form-group">
                <input
                    class="input"
                    type="text"
                    placeholder="请输入用户名"
                    v-model="formData.username"
                />
                <input
                    class="input"
                    password
                    placeholder="请输入密码"
                    v-model="formData.password"
                />
            </view>

            <view v-if="activeTab === 1" class="form-group">
                <input
                    class="input"
                    type="number"
                    placeholder="请输入手机号"
                    v-model="formData.phone"
                    maxlength="11"
                />
                <view class="code-input">
                    <input
                        class="input"
                        type="number"
                        placeholder="请输入验证码"
                        v-model="formData.code"
                    />
                    <text 
                        class="get-code"
                        :class="{ 'disabled': codeCountdown > 0 }"
                        @click="getSmsCode"
                    >{{ codeCountdown > 0 ? `${codeCountdown}s` : '获取验证码' }}</text>
                </view>
            </view>
            <button 
                class="login-btn"
                :loading="loading"
                @click="handleH5Login"
            >立即登录</button>
     
        </view>
        <!-- #endif -->
        <!-- 将原来的注册文本改为可点击的 -->
        <view class="register" @click="handleRegister">注册</view>
        <view v-if="message" :class="['message', messageType]">
            {{ message }}
        </view>
    </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import axios from 'axios'
const { safeAreaInsets } = uni.getSystemInfoSync()

// 响应式数据
const loading = ref(false)
const codeCountdown = ref(0)
const message = ref('')
const messageType = ref('success')
// #ifdef H5
const activeTab = ref(0)
// #endif

const formData = reactive({
    username: '',
    password: '',
    phone: '',
    code: ''
})

// H5登录处理
const handleH5Login = async () => {
    if (activeTab.value === 0) {
        if (!formData.username || !formData.password) {
            return showMessage('请输入用户名和密码')
        }
        try {
            const response = await axios.post('http://localhost:3000/login', {
                username: formData.username,
                password: formData.password
            })
            
            if (response.data.code === 200) {
                showMessage('登录成功', 'success')
                uni.setStorageSync('userInfo', response.data.data)
                setTimeout(() => {
                    uni.switchTab({ url: '/pages/index/index' })
                }, 1500)
            } else {
                showMessage(response.data.message || '用户名或密码错误')
            }

        } catch (error) {
            handleLoginError(error)
        }
    } else {
        if (!formData.phone || !formData.code) {
            return showMessage('请输入手机号和验证码')
        }
        // 手机验证码登录
        try {
            const response = await axios.post('http://localhost:3000/login/phone', {
                phone: formData.phone,
                code: formData.code
            })
            console.log(response,143)   
            handleLoginSuccess(response)
        } catch (error) {
            handleLoginError(error)
        }
    }
}

// 获取验证码
const getSmsCode = async () => {
    if (codeCountdown.value > 0) return
    
    if (!formData.phone) {
        return showMessage('请输入手机号')
    }
    if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
        return showMessage('手机号格式错误')
    }

    loading.value = true
    try {
        const response = await axios.post('http://localhost:3000/send-sms', {
            phoneNumber: formData.phone
        })

        if (response.data.success) {
            showMessage('验证码发送成功', 'success')
            codeCountdown.value = 60
            const timer = setInterval(() => {
                if (codeCountdown.value <= 0) {
                    clearInterval(timer)
                    return
                }
                codeCountdown.value--
            }, 1000)
        } else {
            showMessage(response.data.message || '验证码发送失败')
        }
    } catch (error) {
        showMessage('发送失败，请重试')
    } finally {
        loading.value = false
    }
}



// 小程序登录处理
const handleMiniLogin = async () => {
    if (!formData.username || !formData.password) {
        return showMessage('请输入用户名和密码')
    }

    loading.value = true
    try {
        const response = await uni.request({
            url: 'http://localhost:3000/login',
            method: 'POST',
            data: {
                username: formData.username,
                password: formData.password
            }
        });
        
        if (response.statusCode === 200 && response.data.code === 200) {
            showMessage('登录成功', 'success')
            uni.setStorageSync('userInfo', response.data.data)
            setTimeout(() => {
                uni.switchTab({ url: '/pages/index/index' })
            }, 1500)
        } else {
            showMessage(response.data.message || '用户名或密码错误')
        }
    } catch (error) {
        console.error('登录失败:', error)
        showMessage('登录失败，请重试')
    } finally {
        loading.value = false
    }
}

// 统一处理登录成功
const handleLoginSuccess = (response) => {
    if (response.data.success) {
        showMessage('登录成功', 'success')
        uni.setStorageSync('userInfo', response.data.user)
        setTimeout(() => {
            uni.switchTab({ url: '/pages/index/index' })
        }, 1500)
    } else {
        showMessage(response.data.message || '登录失败')
    }
}

// 统一处理登录错误
const handleLoginError = (error) => {
    console.error('登录失败:', error)
    showMessage('登录失败，请重试')
}

// 显示消息提示
const showMessage = (msg, type = 'error') => {
    message.value = msg
    messageType.value = type
    setTimeout(() => {
        message.value = ''
    }, 3000)
}


// 处理注册跳转
const handleRegister = () => {
    uni.navigateTo({
        url: '/pages/Register/Register'
    })
}
</script>

<style lang="scss" scoped>
.login-container {
    min-height: 100vh;
    background: #f8f8f8;
    
    .header {
        height: 240rpx;
        background: #00c8aa;
        display: flex;
        align-items: center;
        justify-content: center;
        
        .title {
            color: #fff;
            font-size: 40rpx;
            font-weight: bold;
        }
    }
    
    .tab-bar {
        display: flex;
        justify-content: center;
        margin: 40rpx 0;
        
        .tab-item {
            margin: 0 40rpx;
            font-size: 32rpx;
            color: #666;
            padding-bottom: 10rpx;
            
            &.active {
                color: #00c8aa;
                border-bottom: 4rpx solid #00c8aa;
            }
        }
    }
    
    .form-container {
        padding: 0 60rpx;
        
        .form-group {
            margin-bottom: 60rpx;
            
            .input {
                height: 100rpx;
                background: #fff;
                margin-bottom: 30rpx;
                padding: 0 30rpx;
                border-radius: 12rpx;
                font-size: 28rpx;
            }
            
            .code-input {
                position: relative;
                
                .get-code {
                    position: absolute;
                    right: 20rpx;
                    top: 50%;
                    transform: translateY(-50%);
                    color: #00c8aa;
                    font-size: 28rpx;
                }
            }
        }
        
        .login-btn {
            height: 90rpx;
            line-height: 90rpx;
            background: #00c8aa;
            color: #fff;
            font-size: 32rpx;
            border-radius: 45rpx;
        }
        
        .extra-options {
            margin-top: 40rpx;
            display: flex;
            justify-content: space-between;
            color: #00c8aa;
            font-size: 28rpx;
        }
    }
}

// 添加新样式
.message {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    padding: 20rpx 40rpx;
    border-radius: 10rpx;
    font-size: 28rpx;
    z-index: 999;
    
    &.success {
        background: rgba(0, 200, 170, 0.9);
        color: #fff;
    }
    
    &.error {
        background: rgba(255, 0, 0, 0.9);
        color: #fff;
    }
}

.get-code {
    &.disabled {
        color: #999;
    }
}
.register {
    width: 100vw;
    text-align: center;
    color: #00c8aa;
    font-size: 4vw;
    line-height: 10vw;
    cursor: pointer;  // 添加鼠标指针样式
    
    &:active {  // 添加点击效果
        opacity: 0.8;
    }
}
</style>